//
//  MyTodoVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2024/11/12.
//  Copyright © 2024 zwb. All rights reserved.
//
import UIKit

class MyTodoVC: UIViewController,UISearchBarDelegate {
    var searchBar:UISearchBar!
    
    
    lazy var table1:UITableView = {
        let v = UITableView()
        return v
    }()
    lazy var table2: UITableView = {
        let v = UITableView()
        v.frame = view.frame
        
        v.backgroundColor = Theme.GREY
        v.estimatedRowHeight = 120
        v.separatorStyle = .none
        v.tableFooterView = UIView(frame: CGRect.zero)
        return v
    }()
  
    
    var keyword = ""
    var page = 1
    var size = 20
    fileprivate var dataArray = [ToDoModel]()
    
    var selectSection:Int? = nil// 用来处理折叠
    
    var selectInd:IndexPath? = nil// 用来处理过滤
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.table1.mj_header?.beginRefreshing()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Theme.commonBg
   
        self.title = "待办"
        
      
        
        
        
        searchBar = UISearchBar(frame:CGRect(x:0,y:5,width:KSGlobal.screenW,height:40))
        searchBar.inputAccessoryView = KSToolbar(controller: self)
        searchBar.placeholder = "内容搜索"
        searchBar.delegate = self
        searchBar.backgroundImage = UIImage()

        self.view.addSubview(searchBar)
        
        
        table1.delegate = self
        table1.dataSource = self
        table1.separatorStyle = .none
        table1.register(AuditLeftTypeCell.self, forCellReuseIdentifier: AuditLeftTypeCell.identifier)
        table1.register(NewTodoHeader.self, forHeaderFooterViewReuseIdentifier: NewTodoHeader.identifier)
        if #available(iOS 15.0, *) {
            table1.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        table1.rowHeight = 50
        self.view.addSubview(table1)
        table1.snp.makeConstraints { make in
            make.top.equalTo(searchBar.snp.bottom).offset(5)
            make.left.bottom.equalTo(self.view)
            make.width.equalTo(118)
            
        }
        
        
        
        table2.delegate = self
        table2.dataSource = self
        if #available(iOS 15.0, *) {
            table2.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        self.table2.showsVerticalScrollIndicator = false
        self.view.addSubview(table2)
        table2.snp.makeConstraints { make in
            make.top.equalTo(searchBar.snp.bottom)
            make.right.bottom.equalTo(self.view)
            make.left.equalTo(table1.snp.right)
        }
        self.table2.backgroundColor = Theme.awModuleBgColor
        self.table2.separatorStyle = .none
        table2.estimatedRowHeight = 100
        table2.rowHeight = UITableView.automaticDimension
        table2.register(GlobalTableViewCell.self, forCellReuseIdentifier: GlobalTableViewCell.identifier)
        table2.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
        edgesForExtendedLayout = UIRectEdge()
        table1.mj_header = KSRefreshHeader {
      
            self.fetchType()
        }
        table2.mj_header = KSRefreshHeader {
            self.page = 1
            self.fetchDetail()
        }
        table2.mj_footer = KSRefreshFooter {
            self.page += 1
            self.fetchDetail()
        }
        
 
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
 
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        keyword = searchBar.text.unwrap
        self.dataArray.removeAll()
        self.table2.reloadData()
        self.table2.mj_header?.beginRefreshing()
        
    }
    
    
    func fetchType() {
      
        KSNetwork.shared.doRequest(API.auditFlow(.getVocNmWait(page: "1", size: "200", keyword: ""))) { (data:BaseResult<VoccdTypeModel>) in
                if data.flag == TRUE {
                    if let infos = data.infoArrCombine {
                        if auditedDirectory2 {
                            VoccdTree = infos
                        } else {
                            VoccdTree = infos.flatMap { $0.detail }
                        }
                     
                        self.table1.mj_header?.endRefreshing()
                        self.table1.reloadData()
                        self.selectInd = nil
                        self.table2.mj_header?.beginRefreshing()
                    }
                }
                
            }
      
        
        
    }
    func fetchDetail() {
        var vo = ""
        if self.selectInd.isSome {
            
            
            var theone:VoccdTypeModel?
            if auditedDirectory2 {
                theone = VoccdTree[self.selectInd!.section].detail[self.selectInd!.row]
            } else {
                theone = VoccdTree[self.selectInd!.row]

            }
            vo = theone!.voc_cd.unwrap
            self.title = theone!.voc_nm
            
          
        } else {
            self.title = "待办"
        }
        

        
        
        let target = API.auditFlow(.mynotifyByVoc(page: "\(page)", size: "\(size)", keyword: keyword, voc_cd: vo))
        
        
        
        KSNetwork.shared.doRequest(target,showHud: false) {[weak self] (data:BaseResult<ToDoModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    if self.page == 1 {
                        self.dataArray = infos
                    } else {
                        self.dataArray += infos
                    }
                    self.table2.mj_header?.endRefreshing()
                    if infos.count < size {
                        self.table2.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.table2.mj_footer?.endRefreshing()
                    }
                    
                    self.table2.reloadData()
                }
               
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
}

extension MyTodoVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView == table1 {
            if auditedDirectory2 {
                return VoccdTree.count
            } else {
                return 1
            }

        } else {
            return 1
        }
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.table1 {
            
            if auditedDirectory2 {
                if VoccdTree[section].openx {
                    return VoccdTree[section].detail.count
                } else {
                    return 0
                }
            } else {
                return VoccdTree.count
            }
           
        } else {
            return dataArray.count
        }
        
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableView == table1 {
            if auditedDirectory2 {
                return 50
            } else {
                return 0
            }
        } else {
            return 0
        }
        
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if tableView == self.table1 {
            guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: NewTodoHeader.identifier) as? NewTodoHeader else {
                fatalError()
            }
            let imgs = VoccdTree[section].openx ? "w_1" : "w_2"
            headerView.colorV.image = UIImage(named: imgs)
            
            
            headerView.left1.text = "(\(VoccdTree[section].tm.unwrap))\(VoccdTree[section].voc_nm.unwrap)"
            let tap = UITapGestureRecognizer()
            tap.numberOfTapsRequired = 1
            tap.addTap {  _ in
                
                if self.selectSection.isSome {
                    if self.selectSection! == section {
                        VoccdTree[self.selectSection!].openx = false
                        self.selectSection = nil
                        self.reloadSection(section)
                    } else {
                        VoccdTree[self.selectSection!].openx = false
                        self.reloadSection(self.selectSection!)
                        
                        
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
                            VoccdTree[section].openx = true
                            self.reloadSection(section)
                        }
                        
                        
                        self.selectSection = section
                        
                        
                    }
                    
                } else {
                    
                    VoccdTree[section].openx = true
                    self.selectSection = section
                    
                    self.reloadSection(section)
                }
                
                
                
                
                
                
                
            }
            
            headerView.addGestureRecognizer(tap)
            
            return headerView
        } else {
            return nil
        }
    }
    
    func reloadSection(_ sec:Int) {
        self.table1.beginUpdates()
        let set = IndexSet(integer: sec)
        self.table1.reloadSections(set, with: .automatic)
        self.table1.endUpdates()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == self.table1 {
            
            var one:VoccdTypeModel?

            if auditedDirectory2 {
                  one = VoccdTree[indexPath.section].detail[indexPath.row]

            } else {
                  one = VoccdTree[indexPath.row]

            }
             
            guard let cell = tableView.dequeueReusableCell(withIdentifier: AuditLeftTypeCell.identifier, for: indexPath) as? AuditLeftTypeCell else {
                fatalError()
            }
            
            
            
            cell.titleLab.text = one!.voc_nm.unwrap
            cell.numBtn.setTitle("\(one!.tm.unwrap)", for: .normal)
            if self.selectInd == indexPath  {
                cell.setSelectedx(true)
            } else {
                cell.setSelectedx(false)
            }
    
            return cell
        } else {
            let one = self.dataArray[indexPath.row]
            guard let cell = tableView.dequeueReusableCell(withIdentifier: GlobalTableViewCell.identifier, for: indexPath) as? GlobalTableViewCell else {
                fatalError()
            }
            
            var tipS = ""
            if one.auditReturnType == "INFO" {
                tipS = "[知会]"
            } else if one.auditReturnType == "SUCCESS" {
                tipS = "[完成]"
            } else if one.auditReturnType == "ERROR" {
                tipS = "[驳回]"
            } else if one.auditReturnType == "WARNING" {
                tipS = "[待审]"
            }
            
            let tsShow = auditListShow(leftS: one.vouNo.unwrap, rightS: tipS)
            
            let titleAndStatus:(String,String) = tsShow
            
            var contArr:[(String,String?)]
            
            contArr = [
                ("","\(one.vouMemo.unwrap)" )
                
            ]
            
            cell.setDataSource(contentArr: contArr,btnTitleArr: nil,titleAndStatus: titleAndStatus)
            
            cell.setTitleFont(UIFont.boldSystemFont(ofSize: 14))
            
            return cell
        }
        
        
        
        
    }
 
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == table1 {
            self.selectInd = indexPath
            
            self.table1.reloadData()
            if self.table2.mj_header!.isRefreshing {
                
                self.table2.mj_header?.endRefreshing()
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
                    self.dataArray.removeAll()
                    self.table2.reloadData()
                    
                    self.table2.mj_header?.beginRefreshing()
                }
                
            } else {
                self.table2.mj_header?.beginRefreshing()
            }
            
            
        } else {
            tableView.deselectRow(at: indexPath, animated: true)
            
            let one = self.dataArray[indexPath.row]
            
            
            go2AuditForm(one, controller: self)
        }
        
    }
}
 
